import { _decorator, Component, Node, tween, UITransform, Vec3 } from 'cc';
import { PinAction } from './PinAction';
import { AudioManger } from './AudioManger';
import { Clips } from './Enums';
import { Tools } from './Tools';
import { Global } from './Global';

const { ccclass, property } = _decorator;

@ccclass('BucketAction')
export class BucketAction extends Component {

    @property({ type: Node })
    container: Node;

    start() {}

    update(deltaTime: number) {}

    /** 清空容器中的所有子节点 */
    public clear_container() {
        this.container.removeAllChildren();
    }

    /** 一次性放入多个 Pin */
    public put_pins(pins: PinAction[]) {
        pins.forEach(pin => this.put_pin(pin));
    }

    /** 放入单个 Pin，并添加位移动画 */
    public put_pin(pin: PinAction) {
        const targetHolePos = new Vec3(
            Tools.random_between(-20, 20),
            Tools.random_between(-30, 30),
            1
        );

        const worldPos = pin.node.getWorldPosition();
        const uiTransform = this.container.getComponent(UITransform);

        if (!uiTransform) {
            console.warn('UITransform missing on container');
            return;
        }

        const localPos = uiTransform.convertToNodeSpaceAR(worldPos);
        this.container.addChild(pin.node);
        pin.node.setPosition(localPos);

        pin.remove_collider();

        tween(pin.node)
            .to(0.25, { position: targetHolePos }, Global.our_easing)
            .call(() => {
                // 可选：播放音效
                // AudioManger.instance.playSound(Clips.close_screw);
            })
            .start();
    }

    /** 获取指定颜色的 Pin 列表 */
    public get_pin_arr_by_color_id(color_id: number, result: PinAction[]) {
        this._filter_pins(result, pin => pin.pin_color?.id === color_id);
    }

    /** 获取所有有颜色的 Pin 列表 */
    public get_pin_arr(result: PinAction[]) {
        this._filter_pins(result, pin => !!pin.pin_color);
    }

    /** 内部通用方法：筛选 container 中的 pin */
    private _filter_pins(result: PinAction[], condition: (pin: PinAction) => boolean) {
        this.container.children.forEach(child => {
            const pin = child.getComponent(PinAction);
            if (pin && condition(pin)) {
                result.push(pin);
            }
        });
    }
}
